package org.jeecg.modules.device.com.pudong.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.device.com.pudong.entity.DataAhl;
import org.jeecg.modules.device.com.pudong.entity.PudongDeviceData;
import org.jeecg.modules.device.com.pudong.service.IDataAhlService;
import org.jeecg.modules.device.com.pudong.service.IPudongDeviceDataService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;


import org.jeecg.modules.device.com.pudong.vo.PudongDeviceDataPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: pudong_device_data
 * @Author: jeecg-boot
 * @Date:   2024-05-31
 * @Version: V1.0
 */
@Api(tags="pudong_device_data")
@RestController
@RequestMapping("/com.pudong/pudongDeviceData")
@Slf4j
public class PudongDeviceDataController extends JeecgController<PudongDeviceData, IPudongDeviceDataService> {
	@Autowired
	private IPudongDeviceDataService pudongDeviceDataService;

	@Autowired
	private IDataAhlService dataAhlService;


	 /**
	  * 分页列表查询
	  *
	  * @param pudongDeviceData
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "pudong_device_data-分页列表查询")
	 @ApiOperation(value="pudong_device_data-分页列表查询", notes="pudong_device_data-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<?> queryPageList(PudongDeviceData pudongDeviceData,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<PudongDeviceData> queryWrapper = QueryGenerator.initQueryWrapper(pudongDeviceData, req.getParameterMap());
		 Page<PudongDeviceData> page = new Page<PudongDeviceData>(pageNo, pageSize);
		 IPage<PudongDeviceData> pageList = pudongDeviceDataService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  *   添加
	  *
	  * @param pudongDeviceDataPage
	  * @return
	  */
	 @AutoLog(value = "pudong_device_data-添加")
	 @ApiOperation(value="pudong_device_data-添加", notes="pudong_device_data-添加")
	 @PostMapping(value = "/add")
	 public Result<?> add(@RequestBody PudongDeviceDataPage pudongDeviceDataPage) {
		 PudongDeviceData pudongDeviceData = new PudongDeviceData();
		 BeanUtils.copyProperties(pudongDeviceDataPage, pudongDeviceData);
		 pudongDeviceDataService.saveMain(pudongDeviceData, pudongDeviceDataPage.getDataAhlList());
		 return Result.OK("添加成功！");
	 }

	 /**
	  *  编辑
	  *
	  * @param pudongDeviceDataPage
	  * @return
	  */
	 @AutoLog(value = "pudong_device_data-编辑")
	 @ApiOperation(value="pudong_device_data-编辑", notes="pudong_device_data-编辑")
	 @PutMapping(value = "/edit")
	 public Result<?> edit(@RequestBody PudongDeviceDataPage pudongDeviceDataPage) {
		 PudongDeviceData pudongDeviceData = new PudongDeviceData();
		 BeanUtils.copyProperties(pudongDeviceDataPage, pudongDeviceData);
		 PudongDeviceData pudongDeviceDataEntity = pudongDeviceDataService.getById(pudongDeviceData.getId());
		 if(pudongDeviceDataEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 pudongDeviceDataService.updateMain(pudongDeviceData, pudongDeviceDataPage.getDataAhlList());
		 return Result.OK("编辑成功!");
	 }

	 /**
	  *   通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "pudong_device_data-通过id删除")
	 @ApiOperation(value="pudong_device_data-通过id删除", notes="pudong_device_data-通过id删除")
	 @DeleteMapping(value = "/delete")
	 public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		 pudongDeviceDataService.delMain(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  *  批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "pudong_device_data-批量删除")
	 @ApiOperation(value="pudong_device_data-批量删除", notes="pudong_device_data-批量删除")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		 this.pudongDeviceDataService.delBatchMain(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功！");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "pudong_device_data-通过id查询")
	 @ApiOperation(value="pudong_device_data-通过id查询", notes="pudong_device_data-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		 PudongDeviceData pudongDeviceData = pudongDeviceDataService.getById(id);
		 if(pudongDeviceData==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(pudongDeviceData);

	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "小时内分钟降水（软件统计，翻斗）通过主表ID查询")
	 @ApiOperation(value="小时内分钟降水（软件统计，翻斗）主表ID查询", notes="小时内分钟降水（软件统计，翻斗）-通主表ID查询")
	 @GetMapping(value = "/queryDataAhlByMainId")
	 public Result<?> queryDataAhlListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<DataAhl> dataAhlList = dataAhlService.selectByMainId(id);
		 return Result.OK(dataAhlList);
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "数据解析")
	 @ApiOperation(value="数据解析", notes="数据解析")
	 @PutMapping(value = "/analysis")
	 public Result<?> analysis(@RequestParam(name="id",required=true) String id) {
		 PudongDeviceDataPage pudongDeviceDataPage = this.pudongDeviceDataService.analysisData(id);
		 return Result.OK(pudongDeviceDataPage);
	 }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param pudongDeviceData
	  */
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, PudongDeviceData pudongDeviceData) {
		 // Step.1 组装查询条件查询数据
		 QueryWrapper<PudongDeviceData> queryWrapper = QueryGenerator.initQueryWrapper(pudongDeviceData, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 //Step.2 获取导出数据
		 List<PudongDeviceData> queryList = pudongDeviceDataService.list(queryWrapper);
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 List<PudongDeviceData> pudongDeviceDataList = new ArrayList<PudongDeviceData>();
		 if(oConvertUtils.isEmpty(selections)) {
			 pudongDeviceDataList = queryList;
		 }else {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 pudongDeviceDataList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 }

		 // Step.3 组装pageList
		 List<PudongDeviceDataPage> pageList = new ArrayList<PudongDeviceDataPage>();
		 for (PudongDeviceData main : pudongDeviceDataList) {
			 PudongDeviceDataPage vo = new PudongDeviceDataPage();
			 BeanUtils.copyProperties(main, vo);
			 List<DataAhl> dataAhlList = dataAhlService.selectByMainId(main.getId());
			 vo.setDataAhlList(dataAhlList);
			 pageList.add(vo);
		 }

		 // Step.4 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "pudong_device_data列表");
		 mv.addObject(NormalExcelConstants.CLASS, PudongDeviceDataPage.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("pudong_device_data数据", "导出人:"+sysUser.getRealname(), "pudong_device_data"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<PudongDeviceDataPage> list = ExcelImportUtil.importExcel(file.getInputStream(), PudongDeviceDataPage.class, params);
				 for (PudongDeviceDataPage page : list) {
					 PudongDeviceData po = new PudongDeviceData();
					 BeanUtils.copyProperties(page, po);
					 pudongDeviceDataService.saveMain(po, page.getDataAhlList());
				 }
				 return Result.OK("文件导入成功！数据行数:" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
				 return Result.error("文件导入失败:"+e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.OK("文件导入失败！");
	 }

}
